package com.example.cnotebook;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.cnotebook.util.OKHttpUtil;
import com.example.cnotebook.util.UserConstant;

import org.json.JSONException;
import org.json.JSONObject;

public class ReactionActivity extends BaseActivity implements View.OnClickListener, OKHttpUtil.CallBack {
    private ImageView ivBack;
    private EditText etContent;
    private TextView tvContentLength;
    private Button btnSubmit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reaction);

        ivBack = findViewById(R.id.iv_back);
        etContent = findViewById(R.id.et_content);
        tvContentLength = findViewById(R.id.tv_content_length);
        btnSubmit = findViewById(R.id.btn_submit);

        ivBack.setOnClickListener(this);
        btnSubmit.setOnClickListener(this);

        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                int length = s.toString().length();
                tvContentLength.setText(length + "/250");
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.btn_submit:
                try {
                    submit();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    private void submit() throws JSONException {
        String content = etContent.getText().toString();
        if (content.equals("")) {
            Toast.makeText(this, "请输入反馈内容！", Toast.LENGTH_SHORT).show();
            return;
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("content", content);
        jsonObject.put("userId", UserConstant.userInfo.getId());
        OKHttpUtil.post("/user/reaction", jsonObject, this, this);
    }

    @Override
    public void onSuccess(JSONObject response) throws JSONException {
        if (response.getInt("code") == 1000) {
            Toast.makeText(this, "提交成功！", Toast.LENGTH_SHORT).show();
            etContent.setText("");
        }
    }

    @Override
    public void onFailure(int errorNo, String strMsg) {

    }
}
